//
//  SetupVc.swift
//  Pods
//
//  Created by eme on 2017/3/27.
//
//

import UIKit
import UtilCore
import RxSwift
import RickonCore
import ModelProtocol
import BrandonCore

class SetupVc: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var _customTableView: UITableView!

    /*----------------------------   自定义属性区域    ----------------------------*/
    var titleArr = [String]()
    
    
    var loginOutVm:LoginOutVm?
    
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.setNavigationBarHidden(false, animated: true)
//        self.loginoutBtn.titleLabel?.font = UIFont(name: Theme.font.bold, size: 17)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.isHidden = true
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        self.setupTableView()
    }
    func setupTableView(){
        self._customTableView.showsVerticalScrollIndicator = false
        _customTableView.delegate = self
        _customTableView.dataSource = self
    }
    
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        //退出登录
        
        self.loginOutVm = LoginOutVm()

        
        self.loginOutVm?.error.asObserver().subscribe(onNext:{ (error) in
            
            print(error)
            
        }).addDisposableTo(disposeBag)
    }
    //登出
    func loginOut(){
        
        self.loginOutVm?.loginOut_devid.onNext()
        AppData.loginOut()
        self.navigationController?.popViewController(animated: false)
        
    }
    //计算缓存
    func fileSizeOfCache()-> Int {
        
        // 取出cache文件夹目录 缓存文件都在这个目录下
        let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
        //缓存目录路径
        
        // 取出文件夹下所有文件数组
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        
        //快速枚举出所有文件名 计算文件大小
        var size = 0
        for file in fileArr! {
            
            // 把文件名拼接到路径中
            let path = cachePath?.appending("/\(file)")
            // 取出文件属性
            let floder = try! FileManager.default.attributesOfItem(atPath: path!)
            // 用元组取出文件大小属性
            for (abc, bcd) in floder {
                // 累加文件大小
                if abc == FileAttributeKey.size {
                    size += (bcd as AnyObject).integerValue
                }
            }
        }
        
        let mm = size / 1024 / 1024
        
        return mm
    }
    func clearAlert(){
        let alertVC = UIAlertController(title: "清除后，图片等媒体消息需要重新下载查看。确定清除?", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
        //创建按钮
        let acSure = UIAlertAction(title: "清除", style: .destructive) { (UIAlertAction) -> Void in
            self.clearCache()
        }
        let acCancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel,handler: nil)
        alertVC.addAction(acSure)
        alertVC.addAction(acCancel)
        self.present(alertVC, animated: true, completion: nil)
    }
    //删除缓存
    func clearCache() {
        
        // 取出cache文件夹目录 缓存文件都在这个目录下
        let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
        
        // 取出文件夹下所有文件数组
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        // 遍历删除
        for p in fileArr!{
            // 拼接路径
            let path = cachePath?.appendingFormat("/\(p)")
            // 判断是否可以删除
            if(FileManager.default.fileExists(atPath: path!)){
                // 删除
                do {
                    try FileManager.default.removeItem(atPath: path!)
                } catch {
                    
                }
                
            }
        }
        self._customTableView.reloadData()
        self.view.toast("清理成功")
    }
}
extension SetupVc:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 7
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        titleArr = ["个人资料","认证信息","账户安全","意见反馈","关于直供宝","清除缓存"]
        if indexPath.row == 2 || indexPath.row == 4{
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell2") as! Setup_Style2_TableViewCell
            cell.title_Label.text = titleArr[indexPath.row]
            return cell
        }else if indexPath.row != 6{
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! SetupTableViewCell
            cell.title_Label.text = titleArr[indexPath.row]
            if indexPath.row == 1{
                cell.statusLabel.isHidden = false
                if case AppDataState.audited = AppData.appState{
                    cell.statusLabel.text = "已认证"
                    cell.statusLabel.textColor = UIColor(hex:"989898")
                }else if case AppDataState.auditfailed = AppData.appState{
                    cell.statusLabel.text = "审核失败"
                    cell.statusLabel.textColor = UIColor(hex:"e31436")
                }else if case AppDataState.auditing = AppData.appState{
                    cell.statusLabel.text = "审核中"
                    cell.statusLabel.textColor = UIColor(hex:"989898")
                }else if case AppDataState.notAudit = AppData.appState{
                    cell.statusLabel.text = "未认证"
                    cell.statusLabel.textColor = UIColor(hex:"e31436")
                }
                
            }else{
                cell.statusLabel.isHidden = true
            }
            if indexPath.row == 5{
                cell.right_ImageView.isHidden = true
                
                cell.label.normal_fontSize(16)
                cell.label.text = "\(fileSizeOfCache())MB"
                cell.contentView.addSubview(cell.label)
                cell.label.snp.makeConstraints({ (make) in
                    make.right.equalTo(-12.5)
                    make.centerY.equalTo(cell.contentView)
                })
            }
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "cellforButton") as! LogoutTableViewCell
            cell.logoutButton.addTarget(self, action: #selector(SetupVc.loginOut), for: .touchUpInside)
            return cell
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 2 || indexPath.row == 4
        {
            return 54
        }
        else if indexPath.row != 6
        {
            return 45
        }else{
            return 64
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.perform(#selector(SetupVc.deselect), with: nil, afterDelay: 0.1)
        switch indexPath.row {
        case 0:
            _ = "dpxx".openURL()
        case 1:
            if case AppDataState.notAudit = AppData.appState{
                //跳转提交认证资料界面
                _ = "authinfopagevc".openURL(["spid":AppData.loginedUser?.glShop.spid ?? ""])
            }else{
                _ = "certification".openURL()
            }
        case 2:
            _ = "accountsecurity".openURL()
        case 4:
            _ = "aboutmiker".openURL()
        case 3:
            _ = "feedbackVc".openURL()
        case 5:
            clearAlert()
        default:
            break
        }
    }
    func deselect(){
        self._customTableView.deselectRow(at: self._customTableView.indexPathForSelectedRow!, animated: true)
    }
}

